import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image, Modal, Linking } from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
import { Icon } from '@rneui/themed';

// 定义文件对象的接口
interface FileItem {
    url: string;
    name: string;
    size: string | number;
}

// 定义组件的 Props 接口
interface FileViewerProps {
    files: FileItem[];
}

// 文件大小格式化工具
const formatSize = (sizeInBytes: string | number): string => {
    const size = Number(sizeInBytes);
    if (isNaN(size) || size === 0) return '';
    if (size < 1024) return `${size} B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
    return `${(size / (1024 * 1024)).toFixed(2)} MB`;
};

// 判断是否为图片
const isImage = (fileName: string): boolean => {
    return /\.(jpg|jpeg|png|gif|bmp)$/i.test(fileName);
};

export const FileViewer = ({ files }: FileViewerProps) => {
    const [isViewerVisible, setViewerVisible] = useState(false);
    const [viewerIndex, setViewerIndex] = useState(0);

    const imageFiles = files.map(f => ({ url: f.url }));

    const openImageViewer = (index: number) => {
        setViewerIndex(index);
        setViewerVisible(true);
    };

    const handlePreview = async (file: FileItem) => {
        try {
            const supported = await Linking.canOpenURL(file.url);
            if (1) {
                await Linking.openURL(file.url);
            } else {
                console.error(`Don't know how to open this URL: ${file.url}`);
            }
        } catch (error) {
            console.error('An error occurred', error);
        }
    };

    if (!files || files.length === 0) {
        return <Text style={styles.noFilesText}>无</Text>;
    }

    return (
        <View style={styles.container}>
            {files.map((file, index) => (
                <View key={index} style={styles.fileItemContainer}>
                    {isImage(file.name) ? (
                        <TouchableOpacity onPress={() => openImageViewer(index)}>
                            <Image source={{ uri: file.url }} style={styles.imagePreview} />
                        </TouchableOpacity>
                    ) : (
                        <View style={styles.fileIconContainer}>
                            <Icon name="document-text-outline" type="ionicon" color="#666" size={40} />
                        </View>
                    )}
                    <View style={styles.fileInfoContainer}>
                        <Text style={styles.fileName} numberOfLines={2}>{file.name}</Text>
                        <View style={styles.fileMetaContainer}>
                            <Text style={styles.fileSize}>{formatSize(file.size)}</Text>
                            <TouchableOpacity onPress={() => handlePreview(file)}>
                                <Text style={styles.previewLink}>预览</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            ))}

            <Modal visible={isViewerVisible} transparent={true} onRequestClose={() => setViewerVisible(false)}>
                <ImageViewer
                    imageUrls={imageFiles}
                    index={viewerIndex}
                    onCancel={() => setViewerVisible(false)}
                    enableSwipeDown={true}
                    saveToLocalByLongPress={false}
                />
            </Modal>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        width: '100%',
    },
    noFilesText: {
        fontSize: 16,
    },
    fileItemContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 10,
        backgroundColor: '#f9f9f9',
        borderRadius: 8,
        marginBottom: 10,
        borderWidth: 1,
        borderColor: '#eee',
    },
    imagePreview: {
        width: 60,
        height: 60,
        borderRadius: 8,
        backgroundColor: '#e0e0e0',
    },
    fileIconContainer: {
        width: 60,
        height: 60,
        borderRadius: 8,
        backgroundColor: '#e9e9e9',
        justifyContent: 'center',
        alignItems: 'center',
    },
    fileInfoContainer: {
        flex: 1,
        marginLeft: 12,
        justifyContent: 'space-between',
    },
    fileName: {
        fontSize: 15,
        fontWeight: '500',
        color: '#333',
        marginBottom: 8,
    },
    fileMetaContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    fileSize: {
        fontSize: 13,
        color: '#888',
    },
    previewLink: {
        fontSize: 14,
        color: '#007AFF',
        fontWeight: '500',
    },
});